#!/usr/bin/env ruby

##
# Copyright (C) 2014 Hai Bison
#
# See the file LICENSE at the root directory of this project for copying
# permission.
#

require_relative '../code/lib/ga_nuong'
require 'redis'
require 'set'

class Base < GaNuong::Model

    KEYS = { :date_created => Time, :date_modified => Time }
    INDEXES = superclass::INDEXES + Set.new([ :date_created, :date_modified ])

    def initialize hash = nil
        super hash
        self.date_created = Time.now if ! self.date_created
    end # initialize

    def put
        self.date_modified = Time.now
        super
    end # put

end # Base

class Language < Base

    KEYS = superclass::KEYS.merge({ :name => String, :license => String,
            :founders => Set, :date_of_birth => Time })
    COLLECTIONS_TYPES = superclass::COLLECTIONS_TYPES.merge({
            :founders => String })
    INDEXES = superclass::INDEXES + Set.new([ :name, :license, :founders,
            :date_of_birth ])

end # Language

if __FILE__ == $0
    GaNuong.redis = Redis.new

    count = Language.count

    if count.zero?
        # Creates some languages
        Language.new(name: 'Ruby', license: 'BSD',
                     founders: Set.new(['Yukihiro Matsumoto']),
                     date_of_birth: Time.new(1993, 2, 24)).put
        Language.new(name: 'Java', license: 'GPL',
                     founders: Set.new(['James Gosling']),
                     date_of_birth: Time.new(1991, 6, 1)).put
        Language.new(name: 'Python',
                     license: 'Python Software Foundation License',
                     founders: Set.new(['Guido van Rossum']),
                     date_of_birth: Time.new(1989, 12, 1)).put
    # don't have nothing in DB
    else
        random = Random.new
        Language::KEYS.keys.each do |sym|
            ascending = random.rand(999) % 2 == 0
            symbols = Language::KEYS.keys
            id_gt = nil
            id_lt = nil
            limit = nil
            order = { :symbol => sym, :min => 0, :max => Float::MAX,
                      :ascending => ascending }

            puts " > Sort by '#{sym}', #{ascending ? "ascending" : "descending"}:"

            Language.query(symbols=symbols, id_gt=id_gt, id_lt=id_lt,
                           limit=limit, order=order).each do |l|
                s = "%15s: #{l[sym]}" % l.name
                s += " (#{l[sym].to_a})" if l[sym].is_a? Set
                puts s
            end
        end # for each key of Language
    end # have some records in DB
end # if __FILE__ == $0
